export function initTree(arr, checkedIds) {
    checkedIds = checkedIds || [];
    for (let i = 0; i < arr.length; i++) {
        arr[i].label = arr[i].menuName;
        arr[i].value = arr[i].id;
        if (arr[i].group) {
            arr[i].label = arr[i].menuName + ' - ' + arr[i].group;
        }
        if(arr[i].checked){
            checkedIds.push(arr[i].id);
        }
        if (arr[i].children) {
            initTree(arr[i].children, checkedIds);
        }
    }
    return checkedIds;
}

export function findById(items, id){
    for(let i=0;i<items.length;i++){
      if(id == items[i].id){
        return items[i];
      }
      if(items[i].children){
        return findById(items[i].children, id);
      }
    }
    return null;
}

export function findAllParentIds(items, id){
    let parentIds = [];
    items = flattenList(items);

    function traverse(node, id){
        if (Array.isArray(node)) {  
            for (let i = 0; i < node.length; i++) {  
              traverse(node[i], id);  
            }  
        } 
        else {  
            if(id == node.id){
                if(node.parentId == null || node.parentId == '0'){
                    return;
                }else{
                    parentIds.push(node.parentId);
                    traverse(items, node.parentId);
                }
              }
        }
    }

    traverse(items, id);
    return [...new Set(parentIds)];
}

export function flattenList(items){
    let list = [];
    function traverse(node){
        if (Array.isArray(node)) {  
            for (let i = 0; i < node.length; i++) {  
              traverse(node[i]);  
            }  
        } 
        else {  
            list.push({id: node.id, parentId: node.parentId}); 
            if(node.children && node.children.length > 0){
                traverse(node.children);  
            }
        }
    }
    traverse(items);
    return list;
}